package com.zb.kc.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.kc.acl.entity.Permission;
import com.zb.kc.acl.entity.RolePermission;
import com.zb.kc.acl.entity.User;
import com.zb.kc.acl.helper.MenuHelper;
import com.zb.kc.acl.mapper.PermissionMapper;
import com.zb.kc.acl.service.PermissionService;
import com.zb.kc.acl.service.RolePermissionService;
import com.zb.kc.acl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {


    /**
     * 获取所有菜单的方法
     *
     * @return
     */
    @Override
    public Permission queryAllMenu() {
        // 查询出所有的菜单数据
        List<Permission> allMenu = baseMapper.selectList(null);
        // 构建菜单树
        Permission rootMenu = MenuHelper.buildMenuTree(allMenu);
        return rootMenu;
    }

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 根据角色获取菜单
     *
     * @param roleId
     * @return
     */
    @Override
    public Permission selectAllMenu(String roleId) {
        // 根据角色id获取所有的角色权限id
        List<RolePermission> rolePermissions = rolePermissionService
                .list(new QueryWrapper<RolePermission>().eq("role_id", roleId)
                        .select("permission_id"));
        List<String> permissionIds = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        List<Permission> permissions = baseMapper.selectBatchIds(permissionIds);
        permissions.stream().forEach(p -> p.setSelect(true));
        // 构建菜单树
        Permission permission = MenuHelper.buildMenuTree(permissions);
        return permission;
    }

    @Override
    public void saveRolePermissionRealtionShip(String roleId, String[] permissionId) {

    }

    @Override
    public void removeChildById(String id) {

    }


    /**
     * 根据用户id查询菜单权限值permission_value
     *
     * @param id
     * @return
     */
    @Override
    public List<String> selectPermissionValueByUserId(String id) {
        List<String> selectPermissionValueList = null;
        if (this.isSysAdmin(id)) {
            // 如果是系统管理就获取所有权限
            selectPermissionValueList = baseMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = baseMapper.selectPermissionValueByUserId(id);
        }
        return selectPermissionValueList;
    }

    @Autowired
    private UserService userService;

    /**
     * 判断用户是否系统管理员
     *
     * @param userId
     * @return
     */
    private boolean isSysAdmin(String userId) {
        User user = userService.getById(userId);

        if (null != user && "admin".equals(user.getUsername())) {
            return true;
        }
        return false;
    }

    /**
     * 根据用户id 获取菜单树
     *
     * @param id
     * @return
     */
    @Override
    public Permission selectPermissionByUserId(String id) {
        if (this.isSysAdmin(id)) {
            // 所有菜单
            return queryAllMenu();
        }
        List<Permission> permissions = baseMapper.selectPermissionByUserId(id);
        Permission permission = MenuHelper.buildMenuTree(permissions);
        return permission;
    }

    @Override
    public List<Permission> queryAllMenuGuli() {
        return null;
    }

    /**
     * 递归删除菜单
     *
     * @param id
     */
    @Override
    public void removeChildByIdGuli(String id) {
        // 创建list集合，用于封装所有要删除的菜单id值
        List<String> idList = new ArrayList<>();
        // 向idList中设置菜单id
        this.selectPermissionChildById(id, idList);
        baseMapper.deleteBatchIds(idList);
    }

    /**
     * 根据菜单id递归查询所有的子菜单id
     *
     * @param id
     * @param idList
     */
    public void selectPermissionChildById(String id, List<String> idList) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("pid", id);
        wrapper.select("id");
        List<Permission> permissions = baseMapper.selectList(wrapper);
        permissions.stream().forEach(p -> {
            selectPermissionChildById(p.getId(), idList);
        });
        idList.add(id);
    }

    /**
     * 给角色分配菜单
     *
     * @param roleId       角色id
     * @param permissionId 菜单id,数组形式
     */
    @Override
    public void saveRolePermissionRealtionShipGuli(String roleId, String[] permissionId) {
        List<RolePermission> rolePermissions = new ArrayList<>();
        for (int i = 0; i < permissionId.length; i++) {
            RolePermission rp = new RolePermission();
            rp.setRoleId(roleId);
            rp.setPermissionId(permissionId[i]);
            rolePermissions.add(rp);
        }
        rolePermissionService.saveBatch(rolePermissions);
    }
}
